package com.debao.web.controller.debao;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.debao.common.constant.Constants;
import com.debao.common.core.domain.entity.SysUser;
import com.debao.framework.web.service.SysRegisterService;
import com.debao.system.domain.Circle;
import com.debao.system.domain.CourseCard;
import com.debao.system.service.ICourseCardService;
import com.debao.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.debao.common.annotation.Log;
import com.debao.common.core.controller.BaseController;
import com.debao.common.core.domain.AjaxResult;
import com.debao.common.enums.BusinessType;
import com.debao.system.domain.Coach;
import com.debao.system.service.ICoachService;
import com.debao.common.utils.poi.ExcelUtil;
import com.debao.common.core.page.TableDataInfo;

/**
 * 教练Controller
 *
 * @author ruoyi
 * @date 2024-05-31
 */
@RestController
@RequestMapping("/debao/coach")
public class CoachController extends BaseController {
    @Autowired
    private ICoachService coachService;

    @Resource
    private SysRegisterService registerService;
    @Resource
    private ISysUserService userService;

    @Resource
    private ICourseCardService courseCardService;

    /**
     * 查询教练列表
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:list')")
    @GetMapping("/list")
    public TableDataInfo list(Coach coach) {
        startPage();
        List<Coach> list = coachService.selectCoachList(coach);
        return getDataTable(list);
    }

    /**
     * 查询教练列表
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:list')")
    @GetMapping("/all")
    public AjaxResult allList(Coach coach) {
        List<Coach> list = coachService.selectCoachList(coach);
        return AjaxResult.success(list);
    }

    /**
     * 导出教练列表
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:export')")
    @Log(title = "教练", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Coach coach) {
        List<Coach> list = coachService.selectCoachList(coach);
        ExcelUtil<Coach> util = new ExcelUtil<Coach>(Coach.class);
        util.exportExcel(response, list, "教练数据");
    }

    /**
     * 获取教练详细信息
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(coachService.selectCoachById(id));
    }

    /**
     * 新增教练
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:add')")
    @Log(title = "教练", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Coach coach) {
        // 获取用户是否已存在【手机号是否被注册】
        boolean isExist = userService.isExistUser(coach.getPhone());
        // 用户不存在
        if (!isExist) {
            // 开始注册用户 | 注册成功返回
            coach.setUserId(registerService.register(coach.getName(), coach.getPhone()));
            coach.setStatus(1);
            return toAjax(coachService.insertCoach(coach));
        } else {
            // 用户已存在
            SysUser user = userService.getUserByPhone(coach.getPhone());
            if (user != null) {
                coach.setUserId(user.getUserId());
                coach.setStatus(1);
                return toAjax(coachService.insertCoach(coach));
            }
        }
        return AjaxResult.error("新增失败");
    }

    /**
     * 修改教练
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:edit')")
    @Log(title = "教练", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Coach coach) {
        // 获取用户是否已存在【手机号是否被注册】
        boolean isExist = userService.isExistUser(coach.getPhone());
        // 用户存在
        if (isExist) {
            return toAjax(coachService.updateCoach(coach));
        }
        return AjaxResult.error("您输入的手机号还未注册，请先添加教练");
    }

    /**
     * 教练上下线
     *
     * @param id
     * @param status
     * @return
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:upStatus')")
    @GetMapping("/upStatus")
    public AjaxResult editStatus(@RequestParam Long id, @RequestParam Integer status) {
        return toAjax(coachService.updateCoach(new Coach().setId(id).setStatus(status)));
    }

    /**
     * 删除教练
     */
    @PreAuthorize("@ss.hasPermi('debao:coach:remove')")
    @Log(title = "教练", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
//        List<CourseCard> courseCards = courseCardService.selectCourseCardList(new CourseCard().setCoachId(id).setIsDel(Constants.IS_DEL_N));
//        //判断教练是否有课程卡
//        if (courseCards.size() > 0) {
//            return AjaxResult.error("该教练存在课程，请先下架课程后再删除");
//        }
        return toAjax(coachService.deleteCoachById(id));
    }

    /**
     * 审核教练
     */
    @PostMapping("/audit/{id}/{status}")
    public AjaxResult audit(@PathVariable Long id, @PathVariable Integer status) {
        int row = coachService.updateCoach(new Coach().setId(id).setStatus(status));
        if (row == 1) {
            return success();
        }
        return error();
    }

    /**
     * 排序教练
     */
    @PostMapping("/sortAutocarro/{id}/{sort}")
    public AjaxResult sortTeacher(@PathVariable("id") Long id, @PathVariable("sort") Long sort) {
        return toAjax(coachService.updateCoach(new Coach().setId(id).setSortValue(sort)));
    }
}
